var list_product_id = new Array();
var list_product_number = new Array();
var list_product_size = new Array();
var list_product_color = new Array();
var list_product_price = new Array();
var list_product_description = new Array();
var list_product_code = new Array();
var list_product_image = new Array();
var list_product_status = new Array();
var list_customer_order_date = new Array();
var list_received_date = new Array();
var list_saled_date = new Array();
var list_online_date = new Array();
var list_store_date = new Array();
var list_zcod_id = new Array();
var list_price_pt = new Array();
var list_price_at = new Array();
var index = -1;//=-1: chọn sp mới,>=0 : edit sản phẩm
var check_hover_select_name = false;

function moveScroll(){
    var scroll = $(window).scrollTop();
    var anchor_top = $("#maintable").offset().top;
    var anchor_bottom = $("#bottom_anchor").offset().top;
    if (scroll>anchor_top && scroll<anchor_bottom) {
        clone_table = $("#clone");
        if(clone_table.length == 0){
            clone_table = $("#maintable").clone();
            clone_table.attr('id', 'clone');
            clone_table.css({position:'fixed',
                'pointer-events': 'none',
                top:0});
            clone_table.width($("#maintable").width());
            $("#table-container").append(clone_table);
            $("#clone").css({visibility:'hidden'});
            $("#clone thead").css({visibility:'visible'});
        }
    } else {
        $("#clone").remove();
    }
}

$(document).ready(function () {

    $().scroll(moveScroll);

    $("#type_calculate_payment").change(function(){
        var val_status = $(this).val();
        if(val_status == 'pt'){
            $('.mrk_form_calculate_payment').removeClass('hide');
        }else{
            $('.mrk_form_calculate_payment').addClass('hide');
        }

        if(val_status == 'pt' || val_status == 'at' ){
            $('.mrk_form_exchange').removeClass('hide');
        }else{
            $('.mrk_form_exchange').addClass('hide');
        }



    });

    $("#display_color_by_status").change(function () {
        var val_status = $(this).val();
        $(".select_order_status").each(function (index, value) {
            var parent = $(this).parent().parent();
            if (val_status == $(this).val()) {
                $('.color_status', parent).addClass('bg_color_status');
            } else {
                $('.color_status', parent).removeClass('bg_color_status');
            }
        });
    });

    print_address_customer();//print address

    automaticHiddenGroup();//tu dong an 3 nhom khi load site
    $('#datetimepicker_start').datetimepicker({
        maskInput: true, // disables the text input mask
        pickDate: true, // disables the date picker
        pickTime: true, // disables de time picker
        pick12HourFormat: false, // enables the 12-hour format time picker
        pickSeconds: false, // disables seconds in the time picker
        format: 'dd/MM/yyyy hh:mm:ss',
        language: 'en'
    });
    $('#datetimepicker_end').datetimepicker({
        maskInput: true, // disables the text input mask
        pickDate: true, // disables the date picker
        pickTime: true, // disables de time picker
        pick12HourFormat: false, // enables the 12-hour format time picker
        pickSeconds: false, // disables seconds in the time picker
        format: 'dd/MM/yyyy hh:mm:ss',
        language: 'en'
    });
    $('#span_order_payment_date').datetimepicker({
        maskInput: false, // disables the text input mask
        pickDate: true, // disables the date picker
        pickTime: false, // disables de time picker
        pick12HourFormat: false, // enables the 12-hour format time picker
        pickSeconds: false, // disables seconds in the time picker
        format: 'dd/MM/yyyy',
        language: 'en'
    });
    $('#span_payment_date').datetimepicker({
        maskInput: false, // disables the text input mask
        pickDate: true, // disables the date picker
        pickTime: false, // disables de time picker
        pick12HourFormat: false, // enables the 12-hour format time picker
        pickSeconds: false, // disables seconds in the time picker
        format: 'dd/MM/yyyy',
        language: 'en'
    });
    $('input[type="text"]').focus(function () {

        this.select();
    }).blur(function () {
        if (jQuery.trim(this.value) == '') {
            this.value = (this.defaultValue ? this.defaultValue : '');

        }
    });
    //action export to excel
    var act_export_excel = false;
    $("#btn_export_all_excel").click(function () {
        if (act_export_excel === false) {
            act_export_excel = true;
            //            var picker = $('#datetimepicker_start').data('datetimepicker');
//            var start_time = picker.getLocalDate(); // localDate === chon time là time tren local device 2000-01-17 07:00 GMT +7
//            var utcDate = picker.getDate(); // utcDate === time hien thi duoc coi la chon theo mui jo GMT 0 (World Time Standard): 2000-01-17 07:00 GMT 0 -> 2000-01-17 14:00 GMT +7
            start_time = '';
            if ($("#start_time").val() != "start time") {
                start_time = convert_date_to_string($('#datetimepicker_start').data('datetimepicker').getLocalDate());
            }
            end_time = '';
            if ($("#end_time").val() != "end time") {
                end_time = convert_date_to_string($('#datetimepicker_end').data('datetimepicker').getLocalDate());
            }
            $.post("ajax/exportOrderDetailToExcel.php", {
                zen_order_id: $('#zen_order_id').val(),
                by_product_customer: $('#by_product_customer').val(),
                by_payment: $("#by_payment").val(),
                by_order_status: $('#by_order_status').val(),
                by_province: $('#by_province').val(),
                search_text: $("#filter_search_text").val(),
                start_time: start_time,
                end_time: end_time,
                hidden_group_1: $("#hidden_group_1").val(),
                hidden_group_2: $("#hidden_group_2").val(),
                hidden_group_3: $("#hidden_group_3").val(),
                hidden_group_4: $("#hidden_group_4").val()
            }, function (res) {
                if (res.type == 0) {
                    $('#iframe_excel').attr('src', res.url_excel);
                    $('#iframe_excel').load();
                } else {
                    alert(res.msg);
                }
                act_export_excel = false;
            }, "json");

        } else {
            return false;
        }
    });

    //action export to html
//    $('#by_product_customer').on('change', function(e) {
//        if ($(this).val() == 1) {
//            $("#btn_export").show();
//        } else {
//            $("#btn_export").hide();
//        }
//    });

    //order action
    var act_export = false;
    $("#btn_export_html").click(function () {
        if (act_export === false) {
            act_export = true;
            start_time = '';
            if ($("#start_time").val() != "start time") {
                start_time = convert_date_to_string($('#datetimepicker_start').data('datetimepicker').getLocalDate());
            }
            end_time = '';
            if ($("#end_time").val() != "end time") {
                end_time = convert_date_to_string($('#datetimepicker_end').data('datetimepicker').getLocalDate());
            }
            $.post("ajax/exportFilterOrderDetailToHtml.php", {
                zen_order_id: $('#zen_order_id').val(),
                by_product_customer: $('#by_product_customer').val(),
                by_payment: $("#by_payment").val(),
                by_order_status: $('#by_order_status').val(),
                by_province: $('#by_province').val(),
                search_text: $("#filter_search_text").val(),
                start_time: start_time,
                end_time: end_time,
                hidden_group_1: $("#hidden_group_1").val(),
                hidden_group_2: $("#hidden_group_2").val(),
                hidden_group_3: $("#hidden_group_3").val(),
                hidden_group_4: $("#hidden_group_4").val()
            }, function (res) {
                if (res.type == 0) {
                    window.location = res.link;

                } else {
                    alert(res.msg);
                }
                act_export = false;
            }, "json");

        } else {
            return false;
        }
    });

    //fullscreen
    $('#btn_fullscreen').click(function () {
        if ($(this).hasClass('full')) {
            $(this).removeClass('full');
            $(this).html('Fullscreen');
            $("#form_add_customer_order").toggleClass('hidden');
            $(".navbar").toggleClass('hidden');
            $("#div_filter").toggleClass('hidden');
            $('#box_content_customer_order').css("height", '400');
        } else {
            $(this).addClass('full');
            $(this).html('Exit Fullscreen');
            $("#form_add_customer_order").toggleClass('hidden');
            $(".navbar").toggleClass('hidden');
            $("#div_filter").toggleClass('hidden');
            $('#box_content_customer_order').css("height", '1000');
            start_time = '';
            if ($("#start_time").val() != "start time") {
                start_time = convert_date_to_string($('#datetimepicker_start').data('datetimepicker').getLocalDate());
            }
            end_time = '';
            if ($("#end_time").val() != "end time") {
                end_time = convert_date_to_string($('#datetimepicker_end').data('datetimepicker').getLocalDate());
            }
            $.post("ajax/getListCustomerOrderByFilter.php", {
                zen_order_id: $('#zen_order_id').val(),
                by_product_customer: $('#by_product_customer').val(),
                by_payment: $("#by_payment").val(),
                by_order_status: $('#by_order_status').val(),
                by_province: $('#by_province').val(),
                start_time: start_time,
                end_time: end_time,
                page: $("#page_customer_order").val(),
                last_customer_order_id: $("#last_customer_order_id").val(),
                search_text: $("#filter_search_text").val(),
                var_count: $("#var_count").val()
            }, function (res) {
                if (res.type == 0) {
                    $("#last_customer_order_id").val(res.last_customer_order_id);
                    $("#var_count").val(res.var_count);
                    $('#page_customer_order').val(res.page);
                    $('#loadmore_customer_order').val(res.load_more);
                    $("#tbody_order_list").append(res.html);
                    hidden_group();
                    change_order_status();
                    change_order_status_by_customer();
                    update_bought_product_num();
                    edit_bought_product_num();
                    edit_customer_order();
                    delete_order_detail();
                    zoom_photo();
                    popup_zen_payment();
                    popup_edit_note_product();
                    display_color_by_status();
                } else {
                    alert(res.msg);
                }

            }, "json");
        }


    });
    //order action
    var act_order_by = false;
    $("#btn_filter").click(function () {
        if (act_order_by === false) {
            act_order_by = true;
            if ($('#order_by').val() !== 0) {
                $("#status_filter").val("1");
                start_time = '';
                if ($("#start_time").val() != "start time") {
                    start_time = convert_date_to_string($('#datetimepicker_start').data('datetimepicker').getLocalDate());
                }
                end_time = '';
                if ($("#end_time").val() != "end time") {
                    end_time = convert_date_to_string($('#datetimepicker_end').data('datetimepicker').getLocalDate());
                }
                $.post("ajax/getListCustomerOrderByFilter.php", {
                    zen_order_id: $('#zen_order_id').val(),
                    by_product_customer: $('#by_product_customer').val(),
                    by_payment: $("#by_payment").val(),
                    by_order_status: $('#by_order_status').val(),
                    by_category: $('#by_category').val(),
                    by_province: $('#by_province').val(),
                    search_text: $("#filter_search_text").val(),
                    last_customer_order_id: 0,
                    start_time: start_time,
                    end_time: end_time,
                    page: 1,
                    var_count: 0
                }, function (res) {
                    if (res.type == 0) {
                        $("#last_customer_order_id").val(res.last_customer_order_id);
                        $("#var_count").val(res.var_count);
                        $('#page_customer_order').val(res.page);
                        $("#div_total").html(res.html_total_result);
                        $('#loadmore_customer_order').val(res.load_more);

                        $("#total_result").html(res.total_result);
                        $("#tbody_order_list").html(res.html);
                        change_order_status();
                        change_order_status_by_customer();
                        update_bought_product_num();
                        edit_bought_product_num();
                        edit_customer_order();
                        delete_order_detail();
                        zoom_photo();
                        hidden_group();
                        popup_zen_payment();
                        popup_edit_note_product();
                        display_color_by_status();
                        print_address_customer();//print address
                    } else {
                        alert(res.msg);
                    }
                    act_order_by = false;
                }, "json");
            } else {
                alert("Vui lòng chọn cách xắp xếp!");
                act_order_by = false;
            }
        } else {
            return false;
        }
    });

    //reser search and filter
    $(".reset_search_filter").click(function () {
        // reset_filter_search();
        location.reload();
    });
    $(window).scroll(function () {
        $('.icon_scrolltop').show();
    });
    $('.icon_scrolltop').click(function () {
        $("html, body").animate({scrollTop: 0}, "slow", function () {

            $('.icon_scrolltop').hide();
        });


    });

    edit_customer_order();
    delete_order_detail();
    popup_zen_payment();
    popup_edit_note_product();
    zoom_photo();
    change_order_status();
    change_order_status_by_customer();
    //thay đổi số lượng sản phẩm mua được
    update_bought_product_num();
    edit_bought_product_num();

    $('#modal_zen_payment').on('shown', function () {
        $("#content_zen_payment").scrollTop(0);
    });
    $('#modal_zen_payment').on('hidden', function () {
        reload_data_order_by_customer($('#payment_customer_order_id').val());
    });
    //an hien column theo y muon
    action_hidden();
    var act_submit = false;
    $("#save_order_detail").click(function () {
        reset_filter_search();
        if (act_submit === false) {
            act_submit = true;
            if (list_product_id.length > 0) {
                if (checkValidate("#alert-error-order")) {

                    $.post("ajax/checkCustomerInStore.php", {
                        customer_fb_name: $('#customer_fb_name').val(),
                        customer_phone: $('#customer_phone').val(),
                    }, function (res) {
                        if (res.type == 0) {
                            act_submit = false;
                            update_order_detail();
                        } else {
                            act_submit = false;
                            var r = confirm("Cảnh báo trùng số phone!\n Số phone đã tồn tai nhưng có tên FB khác.Ấn tiếp tục để update tên FB mới và thêm đơn hàng cho khách đã tồn tại.Ấn Cancel để hủy.");
                            if (r == true) {
                                update_order_detail();
                            }

//                            $("#dialog-confirm").dialog({
//                                resizable: false,
//                                height: 300,
//                                modal: true,
//                                buttons: {
//                                    "Tiếp tục": function() {
//                                        $(this).dialog("close");
//
//                                        update_order_detail();
//                                    },
//                                    Cancel: function() {
//                                        $(this).dialog("close");
//
//                                    }
//                                }
//                            });
                        }
                    }, "json");

                } else {
                    act_submit = false;
                    return false;
                }
            } else {
                act_submit = false;
                $("#alert-error-order").html("Vui lòng chọn sản phẩm!").show();
                setTimeout(function() {
                    $("#alert-error-order").hide();
                }, 3000);
                hideError(".alert-error-product");
                return false;
            }
        } else {
            return false;
        }
    });
    //get customer info by phone
    var act_get_customer_info = false;
    $("#get_customer_info").click(function () {
        if (act_get_customer_info === false) {
            act_get_customer_info = true;
            if ($('#customer_phone').val() !== "") {
                var numericRegex = /^[0-9-]+$/;
                if (numericRegex.test($('#customer_phone').val())) {
                    var phone = $('#customer_phone').val();
                    search_customer_by_phone(phone);
                    act_get_customer_info = false;

                } else {
                    $("#alert-error-customer").html("Phone chỉ chấp nhận kí tự 0-9!").show();
                    hideError("#alert-error-customer");
                    act_get_customer_info = false;
                }
            } else {
                $("#alert-error-customer").html("Vui lòng điền số phone!").show();
                hideError("#alert-error-customer");
                act_get_customer_info = false;
            }
        } else {
            return false;
        }
    });
    //get customer info by FB name
    var act_get_customer_name = false;
    $("#get_customer_by_name").click(function () {
        if (act_get_customer_name === false) {
            act_get_customer_name = true;
            var fb_name = $('#customer_fb_name').val();
            if ($('#customer_fb_name').val() !== "") {
                $.post("ajax/getCustomerInfoByFbName.php", {
                    fb_name: fb_name
                }, function (res) {
                    if (res.type == 0) {
                        $("#list_customer_fb_name").html(res.html).show();

                        choose_customer_by_fb_name();

                    } else {
                        reset_form();
                        $("#customer_fb_name").val(fb_name);
                        $("#list_customer_fb_name").html('').hide();
                        $("#alert-error-customer").html(res.msg).show();
                        hideError("#alert-error-customer");
                    }
                    act_get_customer_name = false;
                }, "json");

            } else {
                $("#alert-error-customer").html("Vui lòng điền tên FB!").show();
                hideError("#alert-error-customer");
                act_get_customer_name = false;
            }
        } else {
            return false;
        }
    });
    //get product info by code
    var get_product_info = false;
    $("#get_product_info_by_code").click(function () {
        if (get_product_info === false) {
            get_product_info = true;
            if ($('#product_code').val() !== "") {
                getProductInfoByCode($('#product_code').val());
                get_product_info = false;
            } else {
                $(".alert-error-product").html("Vui lòng điền mã sản phẩm!").show();
                hideError(".alert-error-product");
                get_product_info = false;
            }
        } else {
            return false;
        }
    });
    //display product' images
    var get_list_product_image = false;
    $('#choose_imge').click(function (e) {
        if (get_list_product_image === false) {
            get_list_product_image = true;
            e.preventDefault();
            $.post("ajax/getListProductImage.php", {
                page: 1
            }, function (res) {
                if (res.type == 0) {
                    $('#page_image').val(res.page);
                    $('#loadmore_image').val(res.load_more);
                    $("#list_photo_image").html(res.html);
                    $('#photoList').modal('show');
                    choose_image();
                }
                get_list_product_image = false;
            }, "json");

        }
    });
    $('#product_color').on('change', function (e) {
        $.post("ajax/getImageProductByColor.php", {
            product_id: $("#product_id").val(),
            color: $(this).val()
        }, function (res) {
            if (res.type == 0) {
                $("#choose_imge").html(res.product_image);
            } else {
                alert(res.msg);
                return false;
            }
        }, "json");
    });
    var killScroll_list_image = false;
    $('#modal_body_list_image').scroll(function () {
        if ($('#loadmore_image').val() == 1) {
            var height_div_child = $('.gallery').height();
            var height_div_parent = $('.modal-body').height();
            if ($('.modal-body').scrollTop() > (height_div_child - height_div_parent - 10)) {
                if (killScroll_list_image === false) {
                    killScroll_list_image = true;
                    $("#loading").show();
                    $.post("ajax/getListProductImage.php", {
                        page: $('#page_image').val()
                    }, function (res) {
                        if (res.type == 0) {
                            $("#loading").hide();
                            $('#page_image').val(res.page);
                            $('#loadmore_image').val(res.load_more);
                            $("#list_photo_image").append(res.html);
                            choose_image();
                        }
                        killScroll_list_image = false;

                    }, "json");
                } else {
                    return false;
                }
            }
        }
    });

    //add more product
    var act_add_more_product = false;
    $("#add_more_product").click(function () {
        if (act_add_more_product === false) {
            act_add_more_product = true;
            if (checkValidateProduct(".alert-error-product")) {
                if ($("#is_new_product").val() == "1") {
                    //chọn sản phẩm chưa có trong hệ thống
                    act_add_more_product = false;
                    add_new_product_to_order();

                } else {
                    var check_update = 0;//update size, color, photo by color
                    if ($("#main_photo").val() != "") {
                        check_update = 1;
                    }
                    if ($("#new_color").val() != "") {
                        check_update = 1;
                        color = $('#new_color').val();
                    } else {
                        color = $('#product_color').val();
                    }
                    if ($("#new_size").val() != "") {
                        check_update = 1;
                        size = $('#new_size').val();
                    } else {
                        if ($('#product_size').val() == null) {
                            size = '';
                        } else {
                            size = $('#product_size').val();
                        }
                    }
                    //backup array product
                    var temp_list_product_id = list_product_id.splice();
                    var temp_list_product_number = list_product_number.splice();
                    var temp_list_product_size = list_product_size.splice();
                    var temp_list_product_color = list_product_color.splice();
                    var temp_list_product_price = list_product_price.splice();
                    var temp_list_product_description = list_product_description.splice();
                    var temp_list_product_code = list_product_code.splice();
                    var temp_list_product_image = list_product_image.splice();
                    var temp_list_product_status = list_product_status.splice();
                    var temp_list_customer_order_date = list_customer_order_date.splice();
                    var temp_list_received_date = list_received_date.splice();
                    var temp_list_saled_date = list_saled_date.splice();
                    var temp_list_online_date = list_online_date.splice();
                    var temp_list_store_date = list_store_date.splice();
                    var temp_list_zcod_id = list_zcod_id.splice();
                    var temp_list_price_pt = list_price_pt.splice();
                    var temp_list_price_at = list_price_at.splice();

                    //check trùng product id, size,color,order_status
                    var is_exist = 0;
                    var index_exist = 0;
                    for (i = 0; i < list_product_id.length; i++) {
                        if (
                            (list_product_id[i] == $("#product_id").val()) &&
                                (list_product_size[i].toLowerCase() == size.toLowerCase()) &&
                                (list_product_color[i].toLowerCase() == color.toLowerCase()) &&
                                (list_product_price[i] == $('#product_price').val())
                            ) {
                            if (index >= 0) {
                                is_exist = 1;
                                index_exist = i;
                                break;
                            } else {
                                if (list_product_status[i] == 7) {
                                    is_exist = 1;
                                    index_exist = i;
                                    break;
                                }
                            }

                        } else {
                            continue;
                        }

                    }
                    if (index >= 0) {
                        //edit product
                        if (is_exist == 1) {
                            //neu chon sp giong sp da co trong order
                            if (index != index_exist) {
                                //neu khong trung sp dang edit
                                list_product_number[index_exist] = parseInt(list_product_number[index_exist], 10) + parseInt($("#product_number").val(), 10);
                                if ($("#main_photo").val() != "") {
                                    //neu thay anh khac
                                    list_product_image[index_exist ] = $('#product_thumb_image').attr("src");
                                }
                                //neu trung sp da mua khac sp dang edit thi xóa sp dang edit
                                list_product_id.splice(index, 1);
                                list_product_number.splice(index, 1);
                                list_product_size.splice(index, 1);
                                list_product_color.splice(index, 1);
                                list_product_price.splice(index, 1);
                                list_product_description.splice(index, 1);
                                list_product_code.splice(index, 1);
                                list_product_image.splice(index, 1);
                                list_product_status.splice(index, 1);
                                list_customer_order_date.splice(index, 1);
                                list_received_date.splice(index, 1);
                                list_saled_date.splice(index, 1);
                                list_online_date.splice(index, 1);
                                list_store_date.splice(index, 1);
                                list_zcod_id.splice(index, 1);
                                list_price_pt.splice(index, 1);
                                list_price_at.splice(index, 1);
                                index = -1;
                            } else {
                                //trung sp dang edit: only update
                                // list_product_id[index] = $("#product_id").val();
                                list_product_number[index ] = $("#product_number").val();
                                list_product_size[index ] = size;
                                list_product_color[index ] = color;
                                list_product_price[index] = $('#product_price').val();
                                list_product_description[index] = $("#product_description").val();
                                list_product_code[index] = $('#product_code').val();
                                list_product_image[index ] = $('#product_thumb_image').attr("src");
                                list_price_pt[index] = $('#price_pt').val();
                                list_price_at[index] = $('#price_at').val();
                                index = -1;
                            }
                        } else {
                            //thay the sp mới vào sp đang edit
                            list_product_id[index] = $("#product_id").val();
                            list_product_number[index ] = $("#product_number").val();
                            list_product_size[index ] = size;
                            list_product_color[index ] = color;
                            list_product_price[index] = $('#product_price').val();
                            list_product_description[index] = $("#product_description").val();
                            list_product_code[index] = $('#product_code').val();
                            list_product_image[index ] = $('#product_thumb_image').attr("src");
                            list_product_status[index] = 7;
                            list_customer_order_date[index ] = '';
                            list_received_date[index ] = '0000-00-00 00:00:00';
                            list_saled_date[index ] = '0000-00-00 00:00:00';
                            list_online_date[index ] = '0000-00-00 00:00:00';
                            list_store_date[index ] = '0000-00-00 00:00:00';
                            list_zcod_id[index] = 0;
                            list_price_pt[index] = $('#price_pt').val();
                            list_price_at[index] = $('#price_at').val();
                            index = -1;
                        }
                    } else {
                        //insert new product
                        if (is_exist == 1) {
                            //sp moi them da co thi update total product, image,price, AT,PT
                            list_product_number[index_exist] = parseInt(list_product_number[index_exist], 10) + parseInt($("#product_number").val(), 10);
                            list_price_pt[index_exist] = $('#price_pt').val();
                            list_price_at[index_exist] = $('#price_at').val();
                            list_product_price[index_exist] = $('#product_price').val();
                            if ($("#main_photo").val() != "") {
                                list_product_image[index_exist ] = $('#product_thumb_image').attr("src");
                            }
                        } else {
                            //ko bi trung sp thi them moi
                            list_product_id[list_product_id.length ] = $("#product_id").val();
                            list_product_number[list_product_number.length ] = $("#product_number").val();
                            list_product_size[list_product_size.length ] = size;
                            list_product_color[list_product_color.length ] = color;
                            list_product_price[list_product_price.length] = $('#product_price').val();
                            list_product_description[list_product_description.length] = $("#product_description").val();
                            list_product_code[list_product_code.length ] = $('#product_code').val();
                            list_product_image[list_product_image.length ] = $('#product_thumb_image').attr("src");
                            list_product_status[list_product_status.length ] = 7;//trạng thái ORDER
                            list_customer_order_date[list_customer_order_date.length ] = '';
                            list_received_date[list_received_date.length ] = '0000-00-00 00:00:00';
                            list_saled_date[list_saled_date.length ] = '0000-00-00 00:00:00';
                            list_online_date[list_online_date.length ] = '0000-00-00 00:00:00';
                            list_store_date[list_store_date.length ] = '0000-00-00 00:00:00';
                            list_zcod_id[list_zcod_id.length] = 0;
                            list_price_pt[list_price_pt.length] = $('#price_pt').val();
                            list_price_at[list_price_at.length] = $('#price_at').val();
                        }
                    }

                    if (check_update == 1) {
                        //update size,color
                        $.post("ajax/updateAttributeProduct.php", {
                            product_id: $("#product_id").val(),
                            product_size: size,
                            folder_temp: $("#folder_temp").val(),
                            file_main_photo_temp: $("#file_main_photo_temp").val(),
                            product_color: color
                        }, function (res) {
                            if (res.type == 1) {
                                $(".alert-error-product").html(res.msg).show();
                                hideError(".alert-error-product");
                                act_add_more_product = false;
                                //restore array product
                                list_product_id = temp_list_product_id;
                                list_product_number = temp_list_product_number;
                                list_product_size = temp_list_product_size;
                                list_product_color = temp_list_product_color;
                                list_product_price = temp_list_product_price;
                                list_product_description = temp_list_product_description;
                                list_product_code = temp_list_product_code;
                                list_product_image = temp_list_product_image;
                                list_product_status = temp_list_product_status;
                                list_customer_order_date = temp_list_customer_order_date;
                                list_received_date = temp_list_received_date;
                                list_saled_date = temp_list_saled_date;
                                list_online_date = temp_list_online_date;
                                list_store_date = temp_list_store_date;
                                list_zcod_id = temp_list_zcod_id;
                                list_price_pt = temp_list_price_pt;
                                list_price_at = temp_list_price_at;
                                return false;
                            } else {

                                //chi update neu sp nay khong o trang thai het hang
                                if ($("#product_status").val() != 6) {
                                    //auto update AT, PT of product
                                    $.post("ajax/update_at_pt.php", {
                                        product_id: $("#product_id").val(),
                                        store_price: $('#price_pt').val(),
                                        stamp_price: $('#price_at').val()
                                    }, function (res) {
                                        if (res.type == 0) {
                                            for (i = 0; i < list_product_id.length; i++) {
                                                if (list_product_id[i] == $("#product_id").val()) {
                                                    list_price_at[i] = $('#price_at').val();
                                                    list_price_pt[i] = $('#price_pt').val();

                                                }
                                            }
                                            var html = '';
                                            for (var i = 0; i < list_product_id.length; i++) {
                                                html += '<tr id="tr_order_product_'+i+'">' +
                                                    '<td >' + list_product_code[i] + '</td>' +
                                                    '<td class="center">' + list_product_size[i] + '</td>' +
                                                    '<td class="center">' + list_product_number[i] + '</td>' +
                                                    '<td class="center">' + list_product_color[i] + '</td>' +
                                                    '<td class="center"><img src="' + list_product_image[i] + '" width="100px"></td>' +
                                                    '<td class="center">' + list_product_price[i] + '</td>' +
                                                    '<td class="center">' + list_product_description[i] + '</td>' +
                                                    '<td class="center">' +
                                                    '<a  href="javascript:void(0)" class="btn btn-info act_edit_product" rel="' + i + '"><i class="icon-edit icon-white"></i>  Edit</a>' +
                                                    '<a href="javascript:void(0)" class="btn btn-danger act_delete_product" rev="' + list_zcod_id[i] + '" rel="' + i + '"><i class="icon-trash icon-white"></i>Delete</a>' +
                                                    '</td>' +
                                                    '</tr>';
                                            }
                                            $("#tbody_order_product_list").html(html);
                                            delete_order_product();
                                            edit_order_product();
                                            reset_form_product();
                                            act_add_more_product = false;

                                        } else {
                                            alert('Lỗi cập nhật giá AT, PT.');

                                        }

                                    }, "json");
                                }else{
                                    delete_order_product();
                                    edit_order_product();
                                    reset_form_product();
                                    act_add_more_product = false;
                                }
                                $("#product_status").val(0);
                            }


                        }, "json");
                    } else {

                        //chi update neu sp nay khong o trang thai het hang
                        if ($("#product_status").val() != 6) {
                            //auto update AT, PT of product
                            $.post("ajax/update_at_pt.php", {
                                product_id: $("#product_id").val(),
                                store_price: $('#price_pt').val(),
                                stamp_price: $('#price_at').val()
                            }, function (res) {
                                if (res.type == 0) {
                                    for (i = 0; i < list_product_id.length; i++) {
                                        if (list_product_id[i] == $("#product_id").val()) {
                                            list_price_at[i] = $('#price_at').val();
                                            list_price_pt[i] = $('#price_pt').val();

                                        }
                                    }
                                    var html = '';
                                    for (var i = 0; i < list_product_id.length; i++) {
                                        html += '<tr id="tr_order_product_'+i+'">' +
                                            '<td>' + list_product_code[i] + '</td>' +
                                            '<td class="center">' + list_product_size[i] + '</td>' +
                                            '<td class="center">' + list_product_number[i] + '</td>' +
                                            '<td class="center">' + list_product_color[i] + '</td>' +
                                            '<td class="center"><img src="' + list_product_image[i] + '" width="100px"></td>' +
                                            '<td class="center">' + list_product_price[i] + '</td>' +
                                            '<td class="center">' + list_product_description[i] + '</td>' +
                                            '<td class="center">' +
                                            '<a  href="javascript:void(0)" class="btn btn-info act_edit_product" rel="' + i + '"><i class="icon-edit icon-white"></i>  Edit</a>' +
                                            '<a href="javascript:void(0)" class="btn btn-danger act_delete_product" rev="' + list_zcod_id[i] + '" rel="' + i + '"><i class="icon-trash icon-white"></i>Delete</a>' +
                                            '</td>' +
                                            '</tr>';
                                    }
                                    $("#tbody_order_product_list").html(html);
                                    delete_order_product();
                                    edit_order_product();
                                    reset_form_product();
                                    act_add_more_product = false;

                                } else {
                                    alert('Lỗi cập nhật giá AT, PT.');

                                }

                            }, "json");
                        }else{
                            delete_order_product();
                            edit_order_product();
                            reset_form_product();
                            act_add_more_product = false;
                        }
                        $("#product_status").val(0);
                        console.log(list_product_status);
                    }


                }
            } else {

                act_add_more_product = false;
                return false;
            }
        } else {
            return false;
        }
    });
    $('#reset_form_product').click(reset_form_product);
    $('#reset_form').click(reset_form);
    //upload main photo
    var upload_photo = false;
    $('#btn_upload_photo').click(function (e) {
        if (upload_photo === false) {
            upload_photo = true;
            if ($("#main_photo").val() != "") {
                $.post("ajax/uploadProductPhoto.php", {
                    product_photo: encodeURIComponent($("#main_photo").val())
                }, function (res) {
                    if (res.type == 0) {
                        $("#folder_temp").val(res.folder_temp);
                        $("#file_main_photo_temp").val(res.file_name_temp);
                        $("#choose_imge").html('<img id="product_thumb_image" src="' + res.thumb_url + '" width=200px height=200px/>');
                    } else {
                        $(".alert-error-product").html(res.msg).show();
                        hideError(".alert-error-product");

                    }
                    upload_photo = false;
                }, "json");
            } else {
                $(".alert-error-product").html("Vui lòng điền link photo").show();
                hideError(".alert-error-product");
                upload_photo = false;
            }
        }
    });

    //thay đổi ghi chú sản phẩm
    $('#save_note_product').bind('click',function(){
        var $this = $(this);
        if($this.hasClass("disabled")){
            return;
        }else{
            $this.addClass("disabled");
            order_detail_id = $this.data('item-id');
            note =  $("#popup_note_product").val()
            $.post("ajax/updateNoteOrderItemDetail.php", {
                order_detail_id: order_detail_id,
                note: note
            }, function (res) {
                if (res.type == 0) {
                    $this.removeClass("disabled");
                    $('.description_product_detail[data-item-id="'+order_detail_id+'"]').html(escapeHtml(note));
                    $("#modal_zen_edit_note_product").modal("hide");
                } else {
                    $this.removeClass("disabled");
                    $("#alert-error-edit-note_product").html(res.msg).show();
                    hideError("#alert-error-payment");
                    return;
                }

            }, "json");

        }


    });




});

function edit_bought_product_num(){
    $('.mrk_edit_product_num').bind('click',function(){
        var $this = $(this);
        order_detail_id = $this.data('item-id');
        $('#mrk_bought_product_num_'+order_detail_id).show();
        $('.mrk_update_product_num[data-item-id="'+order_detail_id+'"]').show();
        $this.hide();
        return true;
    });
}
function update_bought_product_num(){
    //thay đổi số lượng sản phẩm mua được mrk_update_product_num
    $('.mrk_update_product_num').bind('click',function(){
        var $this = $(this);

        if($this.hasClass("disabled")){
            return false;
        }else{
            $this.addClass("disabled");
            order_detail_id = $this.data('item-id');
            item_num = $('#mrk_bought_product_num_'+order_detail_id).val();
            if(parseInt(item_num)<0){
                alert("Số lượng phải lớn hơn bằng 0!");
                $this.removeClass("disabled");
                return false;
            }else{
                $.post("ajax/updateBoughtProductQuantity.php", {
                    item_id: order_detail_id,
                    quantity: item_num
                }, function (res) {
                    if (res.type == 0) {

                        $this.removeClass("saving");
                        $this.removeClass("disabled");
                        $('#mrk_bought_product_num_'+order_detail_id).hide();
                        $this.hide();
                        $('.mrk_edit_product_num[data-item-id="'+order_detail_id+'"]').show();
                        $('#show_item_product_num_'+order_detail_id).html(item_num);
                        reload_data_order(res.customer_order_id, order_detail_id);
                        return true;
                    } else {
                        $this.removeClass("disabled");
                        alert(res.msg);
                        return false;
                    }

                }, "json");
            }
        }


    });
}

function convert_date_to_string(date_picker) {
    var dd = date_picker.getDate();
    var mm = date_picker.getMonth() + 1; //January is 0!
    var yyyy = date_picker.getFullYear();
    if (dd < 10) {
        dd = '0' + dd;
    }
    if (mm < 10) {
        mm = '0' + mm;
    }
    var hour = date_picker.getHours();
    var min = date_picker.getMinutes();
    var sec = date_picker.getSeconds();
    today = yyyy + '-' + mm + '-' + dd + ' ' + hour + ':' + min + ':' + sec;
    return today;
}
function action_hidden() {
    $(".btn_show_hide_group").click(function () {
        var group = $(this).attr("rel");
        var group_name = $(this).attr("rev");
        if ($("#hidden_group_" + group).val() == 0) {
            $("#hidden_group_" + group).val(1);
            $(this).html('<i class="icon-zoom-in icon-white"></i>Hiện nhóm ' + group_name);


        } else {
            $("#hidden_group_" + group).val(0);
            $(this).html('<i class="icon-zoom-in icon-white"></i>Ẩn nhóm ' + group_name);
        }

        hidden_group();
    });
}
function hidden_group() {
    //an hien nhom 1
    if ($("#hidden_group_1").val() == 1) {
        $(".gp_1").hide();
    } else {
        $(".gp_1").show();
    }
    //an hien nhom 2
    if ($("#hidden_group_2").val() == 1) {
        $(".gp_2").hide();
    } else {
        $(".gp_2").show();
    }
    //an hien nhom 3
    if ($("#hidden_group_3").val() == 1) {
        $(".gp_3").hide();
    } else {
        $(".gp_3").show();
    }
    //an hien nhom 4
    if ($("#hidden_group_4").val() == 1) {
        $(".gp_4").hide();
    } else {
        $(".gp_4").show();
    }

}
function automaticHiddenGroup() {
    $("#hidden_group_" + 1).val(1);
    $("#hidden_group_" + 2).val(1);
    $("#hidden_group_" + 3).val(1);
    $("#hidden_group_" + 4).val(1);
    $('#group_1').html('<i class="icon-zoom-in icon-white"></i>Hiện nhóm PT');
    $('#group_2').html('<i class="icon-zoom-in icon-white"></i>Hiện nhóm AT');
    $('#group_3').html('<i class="icon-zoom-in icon-white"></i>Hiện nhóm VNĐ');
    $('#group_4').html('<i class="icon-zoom-in icon-white"></i>Hiện nhóm địa chỉ');
    hidden_group();
}
function popup_zen_payment() {
    var popup_payment = false;
    if (popup_payment === false) {
        popup_payment = true;
        $(".popup_zen_payment").click(function () {
            $.post("ajax/getPaymentByCustomerOrderID.php", {
                customer_order_id: $(this).attr("rel")
            }, function (res) {
                if (res.type == 0) {
                    $('#payment_id').val(0);
                    $('#payment').val('');
                    $('#payment_customer_order_id').val(res.customer_order_id);
                    $('#box_content_customer_order_payment').html(res.html);
                    $('#payment_customer_name').val(res.customer_name);
                    $("#modal_zen_payment").modal("show");

                    edit_payment();
                    delete_payment();
                } else {
                    alert(res.msg);
                }
                popup_payment = false;
            }, "json");

        });
    }
}

function popup_edit_note_product() {
    var popup_note_product = false;
    if (popup_note_product === false) {
        popup_note_product = true;
        $(".popup_edit_note_product").click(function () {
            var order_detail_id = $(this).attr("rel");
            $.post("ajax/getCustomerOrderItemDetailById.php", {
                order_detail_id: order_detail_id
            }, function (res) {
                if (res.type == 0) {
                    $('#save_note_product').data('item-id',order_detail_id);
                    $('#popup_note_product').val(res.note);
                    $("#modal_zen_edit_note_product").modal("show");

                } else {
                    alert(res.msg);
                }
                popup_note_product = false;
            }, "json");

        });
    }
}

function get_customer_order_detail_by_id(customer_order_id) {
    $.post("ajax/getCustomerOrderDetailByID.php", {
        customer_order_id: customer_order_id
    }, function (res) {
        if (res.type == 0) {
            reset_form();
            if (!$('#div_order_payment').hasClass('hide')) {
                $('#div_order_payment').addClass('hide');//an payment khi edit order
            }
            $('#customer_phone').val(res.phone);
            $("#customer_fb_name").val(res.customer_fb_name);
            $("#customer_name").val(res.customer_name);
            $("#customer_email").val(res.customer_email);
            $("#customer_address").val(res.customer_address);
            $("#customer_id").val(res.customer_id);
            if (res.customer_province == 1) {
                $("#customer_province").prop("checked", true);
                $("#customer_province").parent().addClass("checked");
            } else {
                $("#customer_province").prop("checked", false);
                $("#customer_province").parent().removeClass("checked");
            }
            if (res.customer_wholesale == 1) {
                $("#customer_wholesale").prop("checked", true);
                $("#customer_wholesale").parent().addClass("checked");
            } else {
                $("#customer_wholesale").prop("checked", false);
                $("#customer_wholesale").parent().removeClass("checked");
            }
            $('#order_description').val(res.order_description);
            $('#type_calculate_payment').val(res.type_calculate_payment);
            if(res.type_calculate_payment == 'pt'){
                $('#percent_service').val(res.service_percent);
                $('#fee_weight').val(res.fee_per_kg);
                $('#input_weight').val(res.weight);
                $('.mrk_form_calculate_payment').removeClass('hide');
            }else{
                $('.mrk_form_calculate_payment').addClass('hide');
            }

            if(res.type_calculate_payment == 'pt' || res.type_calculate_payment == 'at'){
                $('#exchange_money').val(res.exchange_money);
                $('.mrk_form_exchange').removeClass('hide');
            }else{
                $('.mrk_form_exchange').addClass('hide');
            }


            list_product_id = res.list_product_id;
            list_product_number = res.list_product_number;
            list_product_size = res.list_product_size;
            list_product_color = res.list_product_color;
            list_product_price = res.list_product_price;
            list_product_description = res.list_product_description;
            list_product_code = res.list_product_code;
            list_product_image = res.list_product_image;
            list_zcod_id = res.list_zcod_id;
            list_product_status = res.list_product_status;
            list_customer_order_date = res.list_customer_order_date;
            list_online_date = res.list_online_date;
            list_store_date = res.list_store_date;
            list_saled_date = res.list_saled_date;
            list_received_date = res.list_received_date;
            list_price_pt = res.list_price_pt;
            list_price_at = res.list_price_at;
            var html = '';
            for (var i = 0; i < list_product_id.length; i++) {
                html += '<tr id="tr_order_product_'+i+'" >' +
                    '<td>' + list_product_code[i] + '</td>' +
                    '<td class="center">' + list_product_size[i] + '</td>' +
                    '<td class="center">' + list_product_number[i] + '</td>' +
                    '<td class="center">' + list_product_color[i] + '</td>' +
                    '<td class="center"><img src="' + list_product_image[i] + '" width="100px"></td>' +
                    '<td class="center">' + list_product_price[i] + '</td>' +
                    '<td class="center">' + list_product_description[i] + '</td>' +
                    '<td class="center">';
                if(list_product_status[i]!=6){
                    html+='<a  href="javascript:void(0)" class="btn btn-info act_edit_product" rel="' + i + '"><i class="icon-edit icon-white"></i>  Edit</a>';
                }

                   html+= '<a href="javascript:void(0)" class="btn btn-danger act_delete_product" rev="' + list_zcod_id[i] + '" rel="' + i + '"><i class="icon-trash icon-white"></i>Delete</a>' +
                    '</td>' +
                    '</tr>';
            }
            $("#tbody_order_product_list").html(html);
            $("#customer_order_id").val(res.customer_order_id);
            $("#h2_title_create_order").html("<i class='icon-edit'></i> Đang sửa chi tiết đơn hàng").css("color", "red");
            $("#btn-minimize-add-order").html('<i class="icon-chevron-up"></i>');
            $("#box-add-customer-order").show();
            delete_order_product();
            edit_order_product();
            $(window).scrollTop(600);
        }

    }, "json");
}
//get detail info customer order
function edit_customer_order() {
    $(".btn_edit_customer_order").unbind('click');
    $('.btn_edit_customer_order').click(function () {
        get_customer_order_detail_by_id($(this).attr('rel'));
    });
}
function update_order_detail() {
    if ($('#customer_province').prop("checked")) {
        provine = 1;
    } else {
        provine = 0;
    }
    if ($('#customer_wholesale').prop("checked")) {
        customer_wholesale = 1;
    } else {
        customer_wholesale = 0;
    }
    payment_date = '';
    if ($("#new_order_payment_date").val() != "Ngày đặt cọc") {
        payment_date = convert_date_to_string($('#span_order_payment_date').data('datetimepicker').getLocalDate());
    }


    $.post("ajax/updateOrderDetail.php", {
        zen_order_id: $('#zen_order_id').val(),
        customer_order_id: $("#customer_order_id").val(),
        customer_fb_name: $('#customer_fb_name').val(),
        customer_name: $('#customer_name').val(),
        customer_email: $('#customer_email').val(),
        customer_phone: $('#customer_phone').val(),
        customer_address: $('#customer_address').val(),
        customer_province: provine,
        customer_wholesale: customer_wholesale,
        order_description: $('#order_description').val(),
        type_calculate_payment: $('#type_calculate_payment').val(),
        percent_service: $('#percent_service').val(),
        fee_weight: $('#fee_weight').val(),
        input_weight: $('#input_weight').val(),
        exchange_money: $('#exchange_money').val(),
        list_product_id: JSON.stringify(list_product_id),
        list_product_number: JSON.stringify(list_product_number),
        list_product_size: JSON.stringify(list_product_size),
        list_product_color: JSON.stringify(list_product_color),
        list_product_price: JSON.stringify(list_product_price),
        list_product_description: JSON.stringify(list_product_description),
        list_product_status: JSON.stringify(list_product_status),
        list_zcod_id: JSON.stringify(list_zcod_id),
        list_customer_order_date: JSON.stringify(list_customer_order_date),
        list_online_date: JSON.stringify(list_online_date),
        list_store_date: JSON.stringify(list_store_date),
        list_saled_date: JSON.stringify(list_saled_date),
        list_received_date: JSON.stringify(list_received_date),
        list_price_pt: JSON.stringify(list_price_pt),
        list_price_at: JSON.stringify(list_price_at),
        payment: $('#new_order_payment').val(),
        type_payment: $('#new_order_type_payment').val(),
        payment_date: payment_date,
        payment_description: $('#new_order_payment_description').val()
    }, function (res) {
        alert(res.msg);
        if (res.type == 0) {
            if ($('#div_order_payment').hasClass('hide')) {
                $('#div_order_payment').removeClass('hide');//hien thi payment khi update order xong
            }
            var customer_order_id = $("#customer_order_id").val();
            reset_form();
            if (customer_order_id == 0) {
                location.reload();
            } else {

                var first_tr = $(".tr_" + customer_order_id + ":first");
                var stt = first_tr.find("td:first").html();
                var pre_tr = first_tr.prev();

                $("#box_content_customer_order").find(".tr_" + customer_order_id).remove();
                $("#btn-minimize-add-order").html('<i class="icon-chevron-down"></i>');
                $("#box-add-customer-order").hide();
                start_time = '';
                if ($("#start_time").val() != "start time") {
                    start_time = convert_date_to_string($('#datetimepicker_start').data('datetimepicker').getLocalDate());
                }
                end_time = '';
                if ($("#end_time").val() != "end time") {
                    end_time = convert_date_to_string($('#datetimepicker_end').data('datetimepicker').getLocalDate());
                }
                $.post("ajax/getInfoOrderByCustomer.php", {
                    zen_order_id: $('#zen_order_id').val(),
                    customer_order_id: customer_order_id,
                    by_product_customer: $('#by_product_customer').val(),
                    by_payment: $("#by_payment").val(),
                    by_order_status: $('#by_order_status').val(),
                    by_province: $('#by_province').val(),
                    search_text: $("#filter_search_text").val(),
                    start_time: start_time,
                    end_time: end_time,
                    stt: stt
                }, function (res) {
                    if (res.type == 0) {
                        $("#div_total").html(res.html_total_result);
                        if (pre_tr.length) {
                            $(".tr_" + customer_order_id).remove();
                            pre_tr.after(res.html);
                        } else {
                            //sua dong dau tien
                            $("#tbody_order_list").prepend(res.html);
                        }

                        hidden_group();
                        change_order_status();
                        change_order_status_by_customer();
                        update_bought_product_num();
                        edit_bought_product_num();
                        edit_customer_order();
                        delete_order_detail();
                        zoom_photo();
                        popup_zen_payment();
                        popup_edit_note_product();
                        display_color_by_status();
                        print_address_customer();
                    } else {
                        alert(res.msg);
                    }

                }, "json");
            }

        } else {
            return false;
        }


    }, "json");
}
function add_new_product_to_order() {
    var array_photo_list = new Array($("#file_main_photo_temp").val());
    var array_photo_color = new Array($("#new_color").val());
    var array_is_main_photo = new Array('1');
    $.post("ajax/updateProduct.php", {
        product_id: 0,
        product_name: $("#product_name").val(),
        link_web: $("#link_web").val(),
        product_code: $("#product_code").val(),
        product_price: $("#product_price").val(),
        store_price: $("#price_pt").val(),
        stamp_price: $("#price_at").val(),
        product_size: $("#new_size").val(),
       // manufacture: $("#manufacture").val(),
        product_category: $("#product_category").val(),
        folder_temp: $("#folder_temp").val(),
        array_photo_list: array_photo_list,
        array_photo_color: array_photo_color,
        array_is_main_photo: array_is_main_photo,
        description: $("#product_description").val(),
        from_order_detail: 1
    }, function (res) {
        act_submit = false;
        if (res.type == 0) {
            list_product_id[list_product_id.length ] = res.product_id;
            list_product_number[list_product_number.length ] = $("#product_number").val();
            list_product_size[list_product_size.length ] = $("#new_size").val();
            list_product_color[list_product_color.length ] = $("#new_color").val();
            list_product_price[list_product_price.length] = $('#product_price').val();
            list_product_description[list_product_description.length] = $("#product_description").val();
            list_product_code[list_product_code.length ] = $('#product_code').val();
            list_product_image[list_product_image.length ] = $('#product_thumb_image').attr("src");
            list_product_status[list_product_status.length ] = 7;//trạng thái ORDER

            list_customer_order_date[list_customer_order_date.length ] = '';
            list_received_date[list_received_date.length ] = '0000-00-00 00:00:00';
            list_saled_date[list_saled_date.length ] = '0000-00-00 00:00:00';
            list_online_date[list_online_date.length ] = '0000-00-00 00:00:00';
            list_store_date[list_store_date.length ] = '0000-00-00 00:00:00';
            list_zcod_id[list_zcod_id.length] = 0;
            list_price_pt[list_price_pt.length] = $('#price_pt').val();
            list_price_at[list_price_at.length] = $('#price_at').val();
            var html = '';
            for (var i = 0; i < list_product_id.length; i++) {
                html += '<tr id="tr_order_product_'+i+'">' +
                    '<td>' + list_product_code[i] + '</td>' +
                    '<td class="center">' + list_product_size[i] + '</td>' +
                    '<td class="center">' + list_product_number[i] + '</td>' +
                    '<td class="center">' + list_product_color[i] + '</td>' +
                    '<td class="center"><img src="' + list_product_image[i] + '" width="100px"></td>' +
                    '<td class="center">' + list_product_price[i] + '</td>' +
                    '<td class="center">' + list_product_description[i] + '</td>' +
                    '<td class="center">' +
                    '<a  href="javascript:void(0)" class="btn btn-info act_edit_product" rel="' + i + '"><i class="icon-edit icon-white"></i>  Edit</a>' +
                    '<a href="javascript:void(0)" class="btn btn-danger act_delete_product" rev="' + list_zcod_id[i] + '" rel="' + i + '"><i class="icon-trash icon-white"></i>Delete</a>' +
                    '</td>' +
                    '</tr>';
            }
            $("#tbody_order_product_list").html(html);
            delete_order_product();
            edit_order_product();
            reset_form_product();
        } else {
            $(".alert-error-product").html(res.msg).show();
            hideError(".alert-error-product");
            act_add_more_product = false;
        }
    }, "json");
}
function reset_form_product() {
    index = -1;//chọn sp từ đầu
    $('#product_code').val('');
    $("#link_web").val('');
    $("#main_photo").val('');
    $("#choose_imge").html('');
    $("#product_size").html('');
    $("#product_color").html('');
    $("#product_price").val('');
    $("#price_pt").val('');
    $("#price_at").val('');
    $('#product_number').val('');
    $("#product_description").val('');
    $("#product_name").val('');
    $("#new_size").val('');
    $("#new_color").val('');
    $("#product_category").val(0);
    $("#folder_temp").val('');
    $("#file_main_photo_temp").val('');
    $("#is_new_product").val("0");
    $(".order_detail_new_product").addClass("hidden");

}
function reset_filter_search() {
    //filter
    $("#filter_search_text").val("");
    $('#by_product_customer').prop('selectedIndex', 0);
    $('#by_payment').prop('selectedIndex', 0);
    $('#by_order_status').prop('selectedIndex', 0);
    $('#by_province').prop('selectedIndex', 0);
    $("#status_filter").val("0");

}
function search_customer_by_phone(phone) {
    $.post("ajax/getCustomerInfoByPhone.php", {
        phone: phone,
        zen_order_id: $("#zen_order_id").val()
    }, function (res) {
        if (res.type == 0) {
            if (res.has_order) {
                get_customer_order_detail_by_id(res.customer_order_id);
            } else {
                reset_form();
                $('#customer_phone').val(res.phone);
                $("#customer_fb_name").val(res.customer_fb_name);
                $("#customer_name").val(res.customer_name);
                $("#customer_email").val(res.customer_email);
                $("#customer_address").val(res.customer_address);
                $("#customer_id").val(res.customer_id);
                if (res.customer_province == 1) {
                    $("#customer_province").prop("checked", true);
                    $("#customer_province").parent().addClass("checked");
                } else {
                    $("#customer_province").prop("checked", false);
                    $("#customer_province").parent().removeClass("checked");
                }
                if (res.customer_wholesale == 1) {
                    $("#customer_wholesale").prop("checked", true);
                    $("#customer_wholesale").parent().addClass("checked");
                } else {
                    $("#customer_wholesale").prop("checked", false);
                    $("#customer_wholesale").parent().removeClass("checked");
                }
            }
        } else {
            reset_form();
            $("#customer_phone").val(phone);
            $("#alert-error-customer").html(res.msg).show();
            hideError("#alert-error-customer");
        }

    }, "json");
}
function choose_customer_by_fb_name() {
    $("#list_customer_fb_name").hover(function () {
        check_hover_select_name = true;
    });
    $(document).mousedown(function () {
        if (check_hover_select_name == false) {
            $("#list_customer_fb_name").hide();
        }
    });
    //$(".list_fb_name").unbind('click');
    $(".list_fb_name").on("click", function () {
        var phone = $(this).attr('rel');
        $("#list_customer_fb_name").hide();
        search_customer_by_phone(phone);
    });
}
function reset_form() {
    reset_form_product();
    //reset form   
    $('#customer_phone').val('');
    $("#customer_fb_name").val('');
    $("#customer_name").val('');
    $("#customer_email").val('');
    $("#customer_address").val('');
    $("#customer_id").val('');
    $("#customer_province").prop("checked", false);
    $("#customer_province").parent().removeClass("checked");
    $("#customer_wholesale").prop("checked", false);
    $("#customer_wholesale").parent().removeClass("checked");
    $('#order_description').val('');
    $("#tbody_order_product_list").html('');
    $("#customer_order_id").val(0);
    $("#h2_title_create_order").html("<i class='icon-edit'></i>  Thêm chi tiết đơn hàng").css("color", "#317EAC");
    list_product_id = new Array();
    list_product_number = new Array();
    list_product_size = new Array();
    list_product_color = new Array();
    list_product_price = new Array();
    list_product_description = new Array();
    list_product_code = new Array();
    list_product_image = new Array();
    list_product_status = new Array();
    list_customer_order_date = new Array();
    list_online_date = new Array();
    list_store_date = new Array();
    list_saled_date = new Array();
    list_received_date = new Array();
    list_zcod_id = new Array();
    list_price_pt = new Array();
    list_price_at = new Array();
    //reset form payment
    $("#new_order_payment").val('');
    $("#new_order_payment_description").val('');
    if ($('#div_order_payment').hasClass('hide')) {
        $('#div_order_payment').removeClass('hide');//hien thi payment khi update order xong
    }
    //reset form type payment
    $("#type_calculate_payment").val('normal');
    $("#percent_service").val('');
    $('#fee_weight').val('');
    $('#input_weight').val('');
    $('.mrk_form_calculate_payment').addClass('hide');
    //reset exchange money
    $('#exchange_money').val('');
    $('.mrk_form_exchange').addClass('hide');
}

function choose_image() {
    var get_product_info = false;
    $(".act_chooes_img").unbind('click');
    $(".act_chooes_img").click(function () {
        if (get_product_info === false) {
            get_product_info = true;
            getProductInfoByCode($(this).attr("rel"));
            $('#photoList').modal('hide');
            get_product_info = false;
        } else {
            return false;
        }
    });
}
function getProductInfoByCode(code) {
    $.post("ajax/getProductInfoByCode.php", {
        product_code: code
    }, function (res) {
        if (res.type == 0) {
            //thêm sản phẩm có sẵn
            $("#is_new_product").val("0");
            $(".order_detail_new_product").addClass("hidden");
            $('#product_code').val(res.product_code);
            $("#choose_imge").html(res.product_image);
            $("#product_size").html(res.product_size);
            $("#product_color").html(res.product_color);
            $("#product_price").val(res.product_price);
            $("#price_pt").val(res.store_price);
            $("#price_at").val(res.stamp_price);
            $("#product_id").val(res.product_id);
        } else {
            //thêm sản phẩm mới
            $("#is_new_product").val("1");
            $(".order_detail_new_product").removeClass("hidden");
            $("#choose_imge").html('');
            $("#product_size").html('');
            $("#product_color").html('');
            $("#product_price").val('');
            $("#price_pt").val('');
            $("#price_at").val('');
            $('#product_number').val('');
            $("#product_description").val('');
            $("#product_category").val('');
            $("#main_photo").val('');
            $("#product_name").val('');
            $(".alert-error-product").html(res.msg).show();
            hideError(".alert-error-product");
        }

    }, "json");
}
function delete_order_product() {
    var act_delete = false;
    $(".act_delete_product").unbind('click');
    $(".act_delete_product").click(function () {
        btn_delete = $(this);
        if (act_delete === false) {
            if (confirm("Are you sure you want to delete this product?")) {

                act_delete = true;
                rel_index = btn_delete.attr("rel");
                var str_id = "#tr_order_product_"+rel_index;
                index_delete = $(".mrk_table_list_order_buy tr").index($(str_id));

                if(index_delete >= 0) {
                    index_delete = index_delete -1;//vị trí tr -1 để ra vị trí trong mảng
                    console.log(list_product_id);
                    list_product_id.splice(index_delete, 1);
                    console.log(list_product_id);
                    list_product_number.splice(index_delete, 1);
                    list_product_size.splice(index_delete, 1);
                    list_product_color.splice(index_delete, 1);
                    list_product_price.splice(index_delete, 1);
                    list_product_description.splice(index_delete, 1);
                    list_product_code.splice(index_delete, 1);
                    list_product_image.splice(index_delete, 1);
                    list_product_status.splice(index_delete, 1);
                    list_customer_order_date.splice(index_delete, 1);
                    list_received_date.splice(index_delete, 1);
                    list_saled_date.splice(index_delete, 1);
                    list_online_date.splice(index_delete, 1);
                    list_store_date.splice(index_delete, 1);
                    list_zcod_id.splice(index_delete, 1);
                    list_price_pt.splice(index_delete, 1);
                    list_price_at.splice(index_delete, 1);
                    btn_delete.parent().parent().remove();
                    act_delete = false;
                }else{
                    alert("có lỗi xảy ra, vui lòng liên hệ Hà Nguyễn");
                }
            } else {
                return false;
            }
        } else {
            return false;
        }
    });
}
function edit_order_product() {
    var act_edit = false;
    $(".act_edit_product").unbind('click');
    $(".act_edit_product").click(function () {
        btn_edit = $(this);

        if (act_edit === false) {
            act_edit = true;
            index = btn_edit.attr("rel");
            $.post("ajax/getProductInfoByCode.php", {
                product_code: list_product_code[index],
                product_color: list_product_color[index]
            }, function (res) {
                if (res.type == 0) {
                    $('#product_code').val(res.product_code);
                    $("#choose_imge").html(res.product_image);
                    $("#product_size").html(res.product_size);
                    $("#product_color").html(res.product_color);
                    $('#product_size option:contains(' + list_product_size[index] + ')').prop('selected', true);
                    $('#product_color option:contains(' + list_product_color[index] + ')').prop('selected', true);
                    $("#product_price").val(list_product_price[index]);
                    $("#price_pt").val(list_price_pt[index]);
                    $("#price_at").val(list_price_at[index]);
                    $("#product_id").val(list_product_id[index]);
                    $("#product_status").val(list_product_status[index]);
                    $('#product_number').val(list_product_number[index]);
                    $("#product_description").val(list_product_description[index]);
                    act_edit = false;
                } else {
                    act_edit = false;
                    $("#choose_imge").html('');
                    $("#product_size").html('');
                    $("#product_color").html('');
                    $("#product_price").val('');
                    $("#price_pt").val('');
                    $("#price_at").val('');
                    $('#product_number').val('');
                    $("#product_description").val('');
                    $(".alert-error-product").html(res.msg).show();
                    hideError(".alert-error-product");
                }

            }, "json");


        } else {
            return false;
        }

    });
}
function checkValidate(id_append) {
    var emailRegex = /^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,6}$/i,
        numericRegex = /^[0-9-]+$/;
    var floatRegex = /^[0-9,.]+$/;
    var check_char = /^[a-zA-Z]+$/;
    var msgEr = '';
    var valueStr = '';
    if ($('input[name="customer_phone"]').val() == '') {
        $(id_append).html("Vui lòng nhập số điện thoại!").show();
        actHideError(id_append, $('input[name="customer_phone"]'));
        return false;
    } else {
        valueStr = $('input[name="customer_phone"]').val();
        if (!numericRegex.test(valueStr)) {
            $(id_append).html("Chỉ nhập số vào ô điện thoại!").show();
            actHideError(id_append, $('input[name="customer_phone"]'));
            return false;
        }

    }
    if ($('input[name="customer_fb_name"]').val() == '') {
        $(id_append).html("Vui lòng nhập tên FB khách hàng!").show();
        actHideError(id_append, $('input[name="customer_fb_name"]'));
        return false;
    }
    if ($('#new_order_payment').val() != '') {
        if ($('#new_order_payment_date').val() == 'Ngày đặt cọc') {
            $(id_append).html("Vui lòng nhập ngày đặt cọc!").show();
            actHideError(id_append, $('#new_order_payment_date'));
            return false;
        }
    }

    if($('#percent_service').val() !=''){
        if (!floatRegex.test($('#percent_service').val())) {
            $(id_append).html("Chỉ nhập số, dấu chấm, dấu phẩy vào ô phần trăm phí!").show();
            actHideError(id_append, $('#percent_service') );
            return false;
        }
    }

    if($('#fee_weight').val() !=''){
        if (!floatRegex.test($('#fee_weight').val())) {
            $(id_append).html("Chỉ nhập số, dấu chấm, dấu phẩy vào ô phần trăm phí!").show();
            actHideError(id_append, $('#fee_weight') );
            return false;
        }
    }

    if($('#percent_service').val() !=''){
        if (!floatRegex.test($('#percent_service').val())) {
            $(id_append).html("Chỉ nhập số, dấu chấm, dấu phẩy vào ô phần trăm phí!").show();
            actHideError(id_append, $('#percent_service') );
            return false;
        }
    }

    return true;
}
function checkValidateProduct(id_append) {
    var emailRegex = /^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,6}$/i,
        numericRegex = /^[0-9,.]+$/;

    var check_char = /^[a-zA-Z]+$/;
    var msgEr = '';
    var valueStr = '';
    if ($("#is_new_product").val() == 1) {
//        if ($("#product_name").val() == '') {
//            $(id_append).html("Vui lòng nhập tên sản phẩm!").show();
//            actHideError(id_append, $("#product_name"));
//            return false;
//        }
        if ($("#product_category").val() == '') {
            $(id_append).html("Vui lòng nhập loại sản phẩm!").show();
            hideError(id_append);
            return false;
        }
        if ($("#file_main_photo_temp").val() == '') {
            $(id_append).html("Vui lòng chọn ảnh đại diện!").show();
            hideError(id_append);
            return false;
        }
        if ($("#new_color").val() == '') {
            $(id_append).html("Vui lòng nhập màu sản phẩm!").show();
            actHideError(id_append, $("#new_color"));
            return false;
        }
    } else {
        if ($("#new_color").val() != '') {
            if ($("#file_main_photo_temp").val() == '') {
                $(id_append).html("Vui lòng chọn ảnh màu tương ứng!").show();
                hideError(id_append);
                return false;
            }
        } else {
            if (!$("#product_color").val()) {
                $(id_append).html("Vui lòng nhập màu sản phẩm!").show();
                actHideError(id_append, $("#product_color"));
                return false;
            }
        }
    }

    if ($("#product_code").val() == '') {
        $(id_append).html("Vui lòng nhập mã sản phẩm!").show();
        actHideError(id_append, $("#product_code"));
        return false;
    }

    if ($('#product_number').val() == '') {
        $(id_append).html("Vui lòng nhập số lượng sản phẩm!").show();
        actHideError(id_append, $('#product_number'));
        return false;
    } else {
        valueStr = $('#product_number').val();
        if (!numericRegex.test(valueStr)) {
            $(id_append).html("Chỉ nhập số vào ô số lượng!").show();
            actHideError(id_append, $('#product_number'));
            return false;
        }

    }
    if ($('#product_price').val() == '') {
        $(id_append).html("Vui lòng nhập giá sản phẩm!").show();
        actHideError(id_append, $('#product_price'));
        return false;
    } else {
        valueStr = $('#product_price').val();
        if (!numericRegex.test(valueStr)) {
            $(id_append).html("Chỉ nhập số vào ô giá!").show();
            actHideError(id_append, $('#product_price'));
            return false;
        }

    }


    return true;
}
var history_status_num = 0;
function change_order_status() {
    $('.select_order_status').unbind("change");
    $('.select_order_status').change(function () {
        var parent = $(this).parent();
        var order_detail_id = $(this).attr("rel");
        item = $(this);
        $.post("ajax/changeOrderStatus.php", {
            id: order_detail_id,
            status: $(this).val()
        }, function (res) {
            if (res.type == 0) {
                history_status_num = history_status_num + 1;
                $(".history_status", parent).html(res.status + "<br/>DONE " + history_status_num).show();
//                if ($("#select_customer_order_status_" + res.customer_order_id).length) {
//                    
//                    $('#select_customer_order_status_' + res.customer_order_id).val(res.select_customer_order_status);
//                }
                if (res.reload_data == 1) {
                    //trạng thái mới hoặc cũ là hết hàng thì phải update lại data
                    if ($("#td_price_" + order_detail_id).length) {
                        $("#td_price_" + order_detail_id).html(res.price);
                    }
                    if ($("#td_store_price_" + order_detail_id).length) {
                        $("#td_store_price_" + order_detail_id).html(res.store_price);
                    }
                    if ($("#td_stamp_price_" + order_detail_id).length) {
                        $("#td_stamp_price_" + order_detail_id).html(res.stamp_price);
                    }
                    reload_data_order(res.customer_order_id, order_detail_id);
                }
                display_color_by_status_item(item);
            } else {
                alert(res.msg);
            }
        }, "json");
    });
}

function reload_data_order(customer_order_id, order_detail_id) {
    start_time = '';
    if ($("#start_time").val() != "start time") {
        start_time = convert_date_to_string($('#datetimepicker_start').data('datetimepicker').getLocalDate());
    }
    end_time = '';
    if ($("#end_time").val() != "end time") {
        end_time = convert_date_to_string($('#datetimepicker_end').data('datetimepicker').getLocalDate());
    }
    $.post("ajax/updateInfoByOrderStatus.php", {
        zen_order_id: $('#zen_order_id').val(),
        order_detail_id: order_detail_id,
        by_product_customer: $('#by_product_customer').val(),
        by_payment: $("#by_payment").val(),
        by_order_status: $('#by_order_status').val(),
        by_province: $('#by_province').val(),
        search_text: $("#filter_search_text").val(),
        start_time: start_time,
        end_time: end_time
    }, function (res) {
        if (res.type == 0) {
            //filter by product
            if ($("#td_total_price_" + order_detail_id).length) {
                $("#td_total_price_" + order_detail_id).html(res.total_price_by_product);
            }
            if ($("#td_total_store_price_" + order_detail_id).length) {
                $("#td_total_store_price_" + order_detail_id).html(res.total_store_price_by_product);
            }
            if ($("#td_total_stamp_price_" + order_detail_id).length) {
                $("#td_total_stamp_price_" + order_detail_id).html(res.total_stamp_price_by_product);
            }
            //filter by customer
            if ($("#td_total_price_" + customer_order_id).length) {
                $("#td_total_price_" + customer_order_id).html(res.total_price);
            }
            if ($("#td_total_store_price_" + customer_order_id).length) {
                $("#td_total_store_price_" + customer_order_id).html(res.total_store_price);
            }
            if ($("#td_total_stamp_price_" + customer_order_id).length) {
                $("#td_total_stamp_price_" + customer_order_id).html(res.total_stamp_price);
            }
            if ($("#td_excess_cash_" + customer_order_id).length) {
                $("#td_excess_cash_" + customer_order_id).html(res.total_excess_cash);
            }
            if ($("#td_debit_" + customer_order_id).length) {
                $("#td_debit_" + customer_order_id).html(res.total_debit);
            }
            if ($("#div_total").length) {
                $("#div_total").html(res.html_total_result);
            }


        } else {
            alert(res.msg);
        }

    }, "json");


}
function change_order_status_by_customer() {
    $('.select_customer_order_status').unbind('change');
    $('.select_customer_order_status').change(function () {
        var customer_order_id = $(this).attr("rel");
        var status = $(this).val();
        $.post("ajax/changeOrderStatusByCustomer.php", {
            customer_order_id: customer_order_id,
            status: status
        }, function (res) {
            if (res.type == 0) {
//                if ($('.common_order_status_' + customer_order_id).length) {
//                    
//                    $('.common_order_status_' + customer_order_id).each(function() {
//                        if ($(this).val() != 6) {
//                            $(this).val(status);
//                        }
//                    });
//                }
//                if (res.reload_data == 1) {
//                    //trạng thái mới hoặc cũ là hết hàng thì phải update lại data
//
//                    reload_data_order_by_customer(res.customer_order_id);
//                }
            } else {
                alert(res.msg);
            }
        }, "json");
    });
}
function reload_data_order_by_customer(customer_order_id) {
    start_time = '';
    if ($("#start_time").val() != "start time") {
        start_time = convert_date_to_string($('#datetimepicker_start').data('datetimepicker').getLocalDate());
    }
    end_time = '';
    if ($("#end_time").val() != "end time") {
        end_time = convert_date_to_string($('#datetimepicker_end').data('datetimepicker').getLocalDate());
    }
    $.post("ajax/updateInfoOrderByCustomer.php", {
        zen_order_id: $('#zen_order_id').val(),
        customer_order_id: customer_order_id,
        by_product_customer: $('#by_product_customer').val(),
        by_payment: $("#by_payment").val(),
        by_order_status: $('#by_order_status').val(),
        by_province: $('#by_province').val(),
        search_text: $("#filter_search_text").val(),
        start_time: start_time,
        end_time: end_time
    }, function (res) {
        if (res.type == 0) {
            for (i = 0; i < res.order_detail_id.length; i++) {
                if ($("#td_price_" + res.order_detail_id[i]).length) {
                    $("#td_price_" + res.order_detail_id[i]).html(res.array_product_price[i]);
                }
            }
            if ($("#td_total_price_" + customer_order_id).length) {
                $("#td_total_price_" + customer_order_id).html(res.total_price);
            }
            if ($("#td_excess_cash_" + customer_order_id).length) {
                $("#td_excess_cash_" + customer_order_id).html(res.total_excess_cash);
            }
            if ($("#td_debit_" + customer_order_id).length) {
                $("#td_debit_" + customer_order_id).html(res.total_debit);
            }
            if ($("#href_payment_" + customer_order_id).length) {
                $("#href_payment_" + customer_order_id).html(res.total_payment);
            }
            if ($("#div_total").length) {
                $("#div_total").html(res.html_total_result);
            }


        } else {
            alert(res.msg);
        }

    }, "json");


}

function zoom_photo() {
    $(".photo_product").click(function () {
        $("#photo_zoom").html('<img width="500px" src="' + $(this).attr('rel') + '">');
        $('#modal_photo_zoom').modal('show');
    });
}
function delete_order_detail() {
    var act_del = false;
    $(".btn_delete_order_detail").unbind('click');
    $(".btn_delete_order_detail").click(function () {
        var btn_del = $(this);
        if (confirm("Are you sure you want to delete this order detail?")) {
            if (act_del === false) {
                act_del = true;
                $.post("ajax/deleteOrderDetail.php", {
                    customer_order_id: $(this).attr('rel')
                }, function (res) {
                    act_del = false;
                    alert(res.msg);
                    if (res.type == 0) {

                        $(".tr_" + btn_del.attr('rel')).remove();
                    }

                }, "json");


            } else {
                return false;
            }
        } else {
            return false;
        }
    });
}
function display_color_by_status() {
    var val_status = $("#display_color_by_status").val();
    $(".select_order_status").each(function (index, value) {
        var parent = $(this).parent().parent();
        if (val_status == $(this).val() && !$(this).hasClass('bg_color_status')) {
            $('.color_status', parent).addClass('bg_color_status');
        } else {
            $('.color_status', parent).removeClass('bg_color_status');
        }
    });
}
function display_color_by_status_item(item) {
    var val_status = $("#display_color_by_status").val();
    var parent = item.parent().parent();
    if (val_status == item.val() && !item.hasClass('bg_color_status')) {
        $('.color_status', parent).addClass('bg_color_status');
    } else {
        $('.color_status', parent).removeClass('bg_color_status');
    }
}
function print_address_customer() {
    $('.print_address_customer').click(function () {
        $.post("ajax/getCustomerAddress.php", {
            customer_id: $(this).attr('rel')
        }, function (res) {
            if (res.type == 0) {
                var mywindow = window.open('', 'Customer Address', 'height=400,width=600');
                mywindow.document.write('<html><head><title>Customer Address</title>');
                mywindow.document.write('</head><body >');
                mywindow.document.write(res.html);
                mywindow.document.write('</body></html>');

                mywindow.print();
                mywindow.close();
            } else {
                alert(res.msg);
            }

        }, "json");
    });
}







 